﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections.Generic;
using ScrumTable.Common.Collections;
using ScrumTable.Common.Logging;

#endregion

namespace ScrumTable.Common.EventHandling
{
    /// <summary>
    /// Contains a not synchronized implementation of an event handler list.
    /// </summary>
    /// <typeparam name="T">Type of the delegate to use.</typeparam>
    public class DelegateHandlerCollection<T> : DisposeBase, IDelegateHandlerCollection<T>
        where T : class
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private readonly Dictionary<object, FastSmartWeakEvent<T>> _events;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new DelegateHandlerCollection instance.
        /// </summary>
        public DelegateHandlerCollection()
            : this(2)
        {
        }

        /// <summary>
        /// Creates a new DelegateHandlerCollection instance.
        /// </summary>
        public DelegateHandlerCollection(int initSize)
        {
            _events = new Dictionary<object, FastSmartWeakEvent<T>>(initSize);
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Checks whether the event with the given key has elements to fire.
        /// </summary>
        /// <param name="key">Key of the delegate to check.</param>
        /// <returns>Returns true if the corresponding event has elements to fire.</returns>
        public bool HasEvents(string key)
        {
            if (_events.ContainsKey(key))
            {
                return !_events[key].IsEmpty;
            }
            return false;
        }

        /// <summary>
        /// Adds a new delegate to the current list.
        /// </summary>
        /// <param name="key">Key of the delegate to add.</param>
        /// <param name="toAdd">Delegate (method pointer) to add.</param>
        public void Add(string key, T toAdd)
        {
            if (!_events.ContainsKey(key))
                _events.Add(key, new FastSmartWeakEvent<T>());

            _events[key].Add(toAdd);
        }

        /// <summary>
        /// Removes a delegate form the current list.
        /// </summary>
        /// <param name="key">Key of the delegate to remove.</param>
        /// <param name="toRemove">Delegate (method pointer) to remove.</param>
        public bool Remove(string key, T toRemove)
        {
            if (_events.ContainsKey(key))
            {
                _events[key].Remove(toRemove);

                if (_events[key].IsEmpty)
                    _events.Remove(key);
                return true;
            }
            return false;
        }

        /// <summary>
        /// Tries to fire a multicast delegate as an event.
        /// </summary>
        /// <param name="key">Key of the delegate to fire.</param>
        /// <param name="sender">Specifies the sender object which should be passed to the delegate.</param>
        /// <param name="args">Specifies the event argument object which should be passed to the delegate.</param>
        /// <returns>
        /// Returns true if the multicast delegate could be fired otherwise false.
        /// </returns>
        public bool TryFire(string key, object sender, EventArgs args)
        {
            if (_events.ContainsKey(key))
            {
                try
                {
                    _events[key].Raise(sender, args);
                    return true;
                }
                catch (Exception e)
                {
                    Logger<DelegateHandlerCollection<T>>.Error(e);
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// Fires a multicast delegate as an event.
        /// </summary>
        /// <param name="key">Key of the delegate to fire.</param>
        /// <param name="sender">Specifies the sender object which should be passed to the delegate.</param>
        /// <param name="args">Specifies the event argument object which should be passed to the delegate.</param>
        /// <returns>
        /// Returns true if the multicast delegate could be fired otherwise false.
        /// </returns>
        public void Fire(string key, object sender, EventArgs args)
        {
            if (_events.ContainsKey(key))
            {
                _events[key].Raise(sender, args);
            }
        }

        /// <summary>
        /// Releases managed (c# or .net) resources.
        /// </summary>
        protected override void ReleaseManagedResources()
        {
            _events.ForEach(pair => pair.Value.Dispose());
            _events.Clear();
        }

        #endregion
    }
}
